<!--
  说明：面试邀约弹窗
 -->
<template>
  <!-- 新建/编辑 -->
  <el-dialog title="面试邀约" :before-close="handleClose" :visible.sync="dialog" width="50%" append-to-body>
    <el-form
      ref="inviteForm"
      :model="inviteForm"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="面试时间" prop="inviteDate">
        <el-date-picker
          v-model="inviteForm.inviteDate"
          type="datetime"
          placeholder="选择面试时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptionStop"
        />
      </el-form-item>
      <el-form-item label="面试职位" prop="jobIndex">
        <el-select v-model="inviteForm.jobIndex" @change="handleSelectJob">
          <el-option
            v-for="(item, index) in jobList"
            :key="item.id"
            :value="index"
            :label="item.jobName"
          >{{ item.jobName }}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="面试方式" prop="inviteWay">
        <el-checkbox-group v-model="inviteForm.inviteWay" style="width: 50%">
          <el-checkbox
            v-for="item in inviteWay"
            :key="item.value"
            :label="item.value"
          >{{ item.label }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="面试城市" prop="city">
        <el-cascader
          v-model="inviteForm.city"
          style="width: 50%"
          :show-all-levels="false"
          :options="provinceAndCityData"
          :props="{ value: 'label' }"
          placeholder="请选择期望城市"
        />
      </el-form-item>
      <el-form-item label="详细地址" prop="workAddress">
        <el-input
          v-model="inviteForm.workAddress"
          type="text"
          maxlength="60"
          placeholder="请输入上班地址"
        />
      </el-form-item>
      <el-form-item label="其他" prop="inviteContent">
        <el-input
          v-model="inviteForm.inviteContent"
          clearable
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 8 }"
          placeholder="请填写内容"
        />
      </el-form-item>
      <el-form-item label="注意事项" prop="noticeItem">
        <el-checkbox-group v-model="inviteForm.noticeItem" style="width: 50%">
          <el-checkbox
            v-for="item in attentionEvent"
            :key="item.value"
            :label="item.value"
          >{{ item.label }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="发送短信通知" prop="isSendMsg">
        <el-checkbox-group v-model="inviteForm.isSendMsg" style="width: 50%">
          <el-checkbox :label="true">是</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="发送邮件通知" prop="isSendEmail">
        <el-checkbox-group v-model="inviteForm.isSendEmail" style="width: 50%">
          <el-checkbox :label="true">是</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <el-row type="flex" class="row-bg" justify="end">
      <el-button @click="handleClose">取消</el-button>
      <el-button @click="reviewHandle">预览</el-button>
      <el-button type="primary" @click="submit">发送邀请</el-button>
    </el-row>
  </el-dialog>
</template>
<script>
import {
  educationOptions,
  studentType,
  workPeriod,
  inviteWay,
  attentionEvent,
  getWorkPeriodName
} from '@/utils/frontDataDict.js'
import { formatTime } from '@/utils/utils'
import { provinceAndCityData } from '@/utils/frontDataDict.js'

import {
  getCompanyByLoginUser,
  getJobExamineDoneList
} from '@/api/company-admin-api/hireManage/index.js'
import { deepClone } from '../../../../utils'
import moment from 'moment'
export default {
  name: 'JobEdit',
  data() {
    return {
      provinceAndCityData: provinceAndCityData,
      pickerOptionStop: {
        disabledDate: (time) => {
          const newTime = new Date()
          return time.getTime() <= newTime
        }
      },
      attentionEvent: attentionEvent, // 注意事项
      inviteWay: inviteWay, // 面试方式
      props: { multiple: true }, // 学历要求多选
      workPeriod: workPeriod, // 工作周期
      studentType: studentType, // 学生类型
      educationOptions: educationOptions, // 学历要求
      dialog: false, //  默认展示，父组件在外面控制展示隐藏
      inviteForm: {
        jobIndex: null,
        inviteDate: null, // 面试时间
        city: [], // 邀约城市
        workAddress: '', // 详细地址
        inviteAddress: '', // 面试地址 = city + workAddress
        inviteWay: ['0'], // 面试方式（多选），inviteWay 0 笔试，1 面试， 2 线上沟通
        inviteContent: '', // 面试描述内容，其他
        noticeItem: ['0'], // 注意事项 0 请带简历、1 请带学生证、2 请带学历证书、3 请带身份证、4 请带作品、5 请着正装
        isSendMsg: true, // todo  '1' 发送 '0' 不发送 缺少是否发送短信的字段
        isSendEmail: false // 是否发送邮件的字段
      },
      // 表单校验
      rules: {
        inviteDate: [
          {
            required: true,
            message: '面试日期不能为空',
            trigger: 'change'
          }
        ],
        inviteWay: [
          {
            required: true,
            type: 'array',
            message: '面试方式不能为空',
            trigger: 'change'
          }
        ],
        jobIndex: [
          {
            required: true,
            message: '面试职位不能为空',
            trigger: 'change'
          }
        ],
        city: [
          { required: true, message: '面试城市不能为空', trigger: 'change' }
        ],
        workAddress: [
          { required: true, message: '详细地址不能为空', trigger: 'blur' }
        ],
        inviteContent: [
          {
            required: false,
            message: '面试内容不能为空',
            trigger: 'blur'
          }
        ],
        noticeItem: [
          {
            required: true,
            type: 'array',
            message: '注意事项不能为空',
            trigger: 'blur'
          }
        ]
      },
      companyInfo: null,
      companyAddress: [], // 企业地址数组，下拉选择
      jobList: [], // 该公司下的所有发布中的职位
      loading: false,
      // 发布中列表参数
      leftQueryParams: {
        pageNo: 1,
        pageSize: 9999,
        flag: ['2'] // 职位状态(string)：0 未发布，1 待审核，2 发布中，3 暂停发布, 4 驳回
      },
      currentJob: null
    }
  },
  methods: {
    reviewHandle() {
      this.$refs.inviteForm.validate((boo) => {
        if (boo) {
          const jobItem = deepClone(this.currentJob)
          const inviteForm = deepClone(this.inviteForm)
          try {
            if (Array.isArray(JSON.parse(jobItem.industry))) {
              jobItem.industry = JSON.parse(jobItem.industry)[1]
            }
          } catch { () => {} }
          try {
            if (Array.isArray(inviteForm.city) && inviteForm.city.length === 2) {
              if (inviteForm.city[0] === inviteForm.city[1]) {
                inviteForm.inviteAddress = inviteForm.city[1] + inviteForm.workAddress
              } else {
                inviteForm.inviteAddress = inviteForm.city.join('') + inviteForm.workAddress
              }
            }
          } catch { () => {} }
          try {
            inviteForm.workPeriod &&
              (inviteForm.workPeriod = getWorkPeriodName(
                inviteForm.workPeriod
              ))
          } catch (error) {
            console.error(new Error('workPeriod不存在'))
          }
          jobItem.publishTime = moment().format('yyyy-MM-DD')
          inviteForm.publishTime &&
            (inviteForm.publishTime = formatTime(
              new Date(inviteForm.publishTime)
            ))
          this.$emit('openReivew', jobItem, inviteForm)
        }
      })
    },
    handleSelectJob() {
      this.currentJob = this.jobList[this.inviteForm.jobIndex]
    },
    // 获取企业下面的发布中职位列表
    getJoblistBycompany() {
      this.loading = true
      // 处理查询参数
      const params = deepClone(this.leftQueryParams)
      // 执行查询
      return getJobExamineDoneList(params).then((res) => {
        res.data.list = res.data.list.map((item) => {
          try {
            item.workPosition = JSON.parse(item.city).join('-')
          } catch (error) {
            item.workPosition = '--'
          }
          return item
        })
        this.jobList = res.data.list
        this.loading = false
      })
    },
    // 获取企业介绍信息接口，拿到企业地址用来下拉选择
    getCompanyRecommentInfo() {
      return getCompanyByLoginUser().then((res) => {
        if (res.code === 0 && res.data) {
          this.companyInfo = res.data
        }
      })
    },
    async open() {
      await this.getCompanyRecommentInfo() // 获取企业地址
      await this.getJoblistBycompany() // 获取企业已发布职位
      this.inviteForm = Object.assign({}, this.$options.data().inviteForm)
      try {
        this.companyAddress = JSON.parse(this.companyInfo.companyAddress) || []
        this.companyAddress.map((item, index) => {
          item.label = item.province + item.city + item.address
          item.value = index
          return item
        })
      } catch (error) {
        console.error(new Error('公司地址不存在'))
      }
      this.dialog = true
    },
    handleClose() {
      this.$refs.inviteForm.resetFields()
      this.dialog = false
    },
    close() {
      this.inviteForm = Object.assign({}, this.$options.data().inviteForm)
      this.dialog = false
      this.$emit('close')
    },
    submit() {
      this.$refs.inviteForm.validate((boo) => {
        if (boo) {
          const inviteForm = deepClone(this.inviteForm)
          inviteForm.inviteWay = JSON.stringify(inviteForm.inviteWay) // 面试方式
          inviteForm.noticeItem = JSON.stringify(inviteForm.noticeItem) // 面试注意事项
          if (Array.isArray(inviteForm.city) && inviteForm.city.length === 2) {
            if (inviteForm.city[0] === inviteForm.city[1]) {
              inviteForm.inviteAddress = inviteForm.city[1] + inviteForm.workAddress
            } else {
              inviteForm.inviteAddress = inviteForm.city.join('') + inviteForm.workAddress
            }
          }
          inviteForm.isSendMsg = inviteForm.isSendMsg ? '1' : '0' // isSendMsg: '1' 发送 '0' 不发送 缺少是否发送短信的字段
          inviteForm.isSendEmail = inviteForm.isSendEmail ? '1' : '0'
          delete inviteForm.jobIndex
          this.$emit('submit', inviteForm, this.currentJob)
        }
      })
    }
  }
}
</script>
